package com.heo.coder;

import java.util.List;
import org.apache.log4j.Logger;

import com.heo.coder.packet.SocketPacket;
import com.heo.coder.packet.base.BasePacket;
import com.heo.util.ByteHelper;
import com.heo.util.Utils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class HuaFuDeviceDecoder extends ByteToMessageDecoder {

	private static Logger log = Logger.getLogger(HuaFuDeviceDecoder.class);

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		if (in.readableBytes() < BasePacket.START_MARKER_LENGTH) {
			return;
		}

		in.markReaderIndex();

		byte[] startByte = new byte[BasePacket.START_MARKER_LENGTH];
		in.readBytes(startByte);

		String startCode = ByteHelper.byteToHexStringNoSpace(startByte);

		if (!BasePacket.START_MARKER_LENGTH_CODE.equals(startCode)) {
			ctx.close();
			return;
		}

		if (in.readableBytes() < BasePacket.HEAD_LENGTH) {
			in.resetReaderIndex();
			return;
		}

		
		byte[] headByte = new byte[BasePacket.HEAD_LENGTH];
		in.readBytes(headByte);
		String headCode = ByteHelper.byteToHexStringNoSpace(headByte);
		if (!Utils.checkNull(headCode)) {
			in.resetReaderIndex();
			return;
		}
		String lengthStr = headCode.substring(0, 2);
		int total = ByteHelper.hex16ToInt(lengthStr);
		String crcStr = headCode.substring(2, 6);
		String control = headCode.substring(6, 8);
		int bodyLength = total - BasePacket.START_MARKER_LENGTH - BasePacket.HEAD_LENGTH;
		String msgContent = "";
		if (bodyLength > 0) {
			if (in.readableBytes() < bodyLength) {
				in.resetReaderIndex();
				return;
			}
			byte[] contentByte = new byte[bodyLength];
			in.readBytes(contentByte);
			msgContent = ByteHelper.byteToHexStringNoSpace(contentByte);
		}

		String data = startCode + lengthStr + crcStr + control + msgContent;
		String check = ByteHelper.byteToHexStringNoSpace(ByteHelper.checkSum(ByteHelper.hexStringToBytes(data), BasePacket.PASS));
//		System.out.println("校验码 = " + checkCode + "，校验和=" + check);
		if(!check.equals(crcStr)) {
			return;
		}
		
		SocketPacket socketPacket = new SocketPacket(lengthStr, bodyLength, crcStr, control, msgContent);
//		socketPacket.setMacAddress("00" + id);
	    out.add(socketPacket);
	}
}
